<template>
  <el-dialog
    v-model="imageDialogVisible"
    title="会议室环境"
    width="60%"
    class="image-dialog"
  >
    <div class="image-viewer bg-blue-1">
      <el-icon class="arrow left" @click="prevImage"><ArrowLeft /></el-icon>
      <div class="image-container">
        <el-image
          :src="currentImageList[currentIndex]"
          fit="contain"
          class="preview-image"
        />
        <el-icon class="delete-icon" @click="handleDeleteImage">
          <Close />
        </el-icon>
      </div>
      <el-icon class="arrow right" @click="nextImage"><ArrowRight /></el-icon>
      <div class="pagination">
        {{ currentIndex }} / {{ imageCounts[currentRoomId] }}
      </div>
    </div>
  </el-dialog>

  <el-dialog v-model="dialogVisible" title="修改会议室信息" width="30%">
    <el-form :model="editForm" label-width="100px">
      <el-form-item label="会议室名称">
        <el-input v-model="editForm.name" />
      </el-form-item>
      <el-form-item label="容纳人数">
        <el-input v-model="editForm.capacity" type="number" />
      </el-form-item>
      <el-form-item label="每小时价格">
        <el-input v-model="editForm.pricePerHour" type="number" />
      </el-form-item>
      <el-form-item label="会议室类型">
        <el-radio-group v-model="editForm.type">
          <el-radio :label="0">教室型</el-radio>
          <el-radio :label="1">会议室型</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <div class="meeting-container">
    <div
      style="display: flex; justify-content: space-between; margin-bottom: 20px"
    >
      <div>
        <el-input
          v-model="searchQuery"
          placeholder="请输入会议室名称"
          style="width: 200px; margin-right: 10px"
        ></el-input>
        <el-button
          type="primary"
          @click="handleSearch"
          :icon="Refresh"
        ></el-button>
      </div>
      <div>
        <el-button type="primary" @click="addDialogVisible = true"
          >新增会议室</el-button
        >
        <el-dropdown>
          <el-button type="primary" @click="handleDeviceInfo"
            >设备管理</el-button
          >
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>
                <el-button @click="handleAddDevice" :icon="Plus"></el-button>
              </el-dropdown-item>
              <el-dropdown-item
                v-for="(device, index) in deviceList"
                :key="index"
                @click.stop="selectedDeviceId = device.deviceId"
                :class="{
                  'selected-device': selectedDeviceId === device.deviceId,
                }"
              >
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 100%;
                  "
                >
                  <span>{{ device.name }}</span>
                  <el-button
                    size="small"
                    type="danger"
                    :icon="Minus"
                    @click.stop="handleRemoveDevice(device.deviceId)"
                  />
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <el-dialog v-model="addDialogVisible" title="新增会议室" width="30%">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="会议室名称">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="容纳人数">
          <el-input v-model="addForm.capacity" type="number" />
        </el-form-item>
        <el-form-item label="每小时价格">
          <el-input v-model="addForm.pricePerHour" type="number" />
        </el-form-item>
        <el-form-item label="会议室类型">
          <el-radio-group v-model="addForm.type">
            <el-radio :label="0">教室型</el-radio>
            <el-radio :label="1">会议室型</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="replyDialogVisible" title="回复评论" width="40%">
      <el-input
        v-model="replyContent"
        type="textarea"
        :rows="4"
        placeholder="请输入回复内容"
      />
      <template #footer>
        <el-button @click="replyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitReply">提交</el-button>
      </template>
    </el-dialog>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else class="meeting-list">
      <div
        v-for="(room, index) in meetingRooms"
        :key="index"
        class="meeting-card"
      >
        <img
          :src="getRoomImage(room.type)"
          alt="会议室图片"
          class="room-image"
        />
        <div class="room-info">
          <h3>{{ room.name }}</h3>
          <p>容量: {{ room.capacity }}人</p>
          <p>价格: ￥{{ room.pricePerHour }}/小时</p>
          <p :class="'status-' + room.status">
            {{ getStatusText(room.status) }}
          </p>
        </div>
        
        <el-upload
          class="upload-button"
          :action="'/api/admin/meetingRoom/addImg'"
          :data="{ roomId: room.roomId }"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
        >
          <el-button type="primary">上传内部图片</el-button>
        </el-upload>
        
        <div class="room-actions">
          <button @click="handleDelete(room.roomId)">删除</button>
          <button @click="handleEdit(room)">修改</button>
          <button @click="handleMtDeviceInfo(room)">设备信息</button>
          <button @click="handleViewEnvironment(room)">
            内部环境({{ imageCounts[room.roomId] || 0 }})
          </button>
          <button @click="handleViewComments(room)">
            评论({{ commentCounts[room.roomId] || 0 }})
          </button>
          <button @click="handleViewStatus(room)">查看状态</button>
          <el-dialog v-model="statusDialogVisible" title="会议室状态" width="70%">
            <div style="margin-bottom: 20px">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期时间"
                end-placeholder="结束日期时间"
              />
              <el-button @click="handleRefreshStatus" style="margin-left: 10px">刷新</el-button>
            </div>
            <el-table :data="statusData" border style="width: 100%">
              <el-table-column prop="startTime" label="开始时间" width="200" />
              <el-table-column prop="endTime" label="结束时间" width="200" />
              <el-table-column prop="statusText" label="状态">
                <template #default="{ row }">
                  <el-tag :type="getStatusColor(row.status)">{{ row.statusText }}</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-dialog>
          <el-dialog
            v-model="commentDialogVisible"
            title="会议室评论"
            width="50%"
          >
            <div class="comment-list">
              <div
                v-for="comment in commentList"
                :key="comment.commentId"
                class="comment-item"
              >
                <div
                  class="comment-header"
                  style="font-weight: bold; color: black"
                >
                  {{ comment.commitName }}
                </div>
                <div class="comment-meta" style="color: blue; font-size: 12px">
                  在{{ comment.useAt }}使用了该会议室后发布这个{{
                    comment.likesCount
                  }}星评价，发布时间{{ comment.createAt }}
                </div>
                <div class="comment-content">
                  {{ comment.content }}
                </div>
                <el-button
                  type="text"
                  @click="toggleSubComments(comment.commentId)"
                  style="font-size: 12px"
                >
                  {{
                    expandedComments[comment.commentId] ? "收起" : "展开"
                  }}评论
                </el-button>
                <div
                  v-if="expandedComments[comment.commentId]"
                  class="sub-comments"
                  style="padding-left: 20px"
                >
                  <div
                    v-for="subComment in subComments[comment.commentId]"
                    :key="subComment.commentId"
                    class="sub-comment-item"
                  >
                    <div style="font-size: 12px">
                      {{ subComment.commitName }}（{{
                        subComment.commitRole === 1 ? "客户" : "公司人员"
                      }}）回复{{ subComment.replyerName }} 于
                      {{ subComment.createAt }}
                    </div>
                    <div>{{ subComment.content }}</div>
                    <el-button
                      type="text"
                      size="small"
                      @click="
                        handleReplySubComment(
                          subComment.commentId,
                          comment.commentId
                        )
                      "
                      >回复</el-button
                    >
                  </div>
                </div>
              </div>
            </div>
            <div class="comment-pagination">
              <el-pagination
                :total="commentPagination.totalCount"
                :page-size="commentPagination.pageSize"
                :current-page="commentPagination.pageNo"
                @current-change="handleCommentPageChange"
                layout="prev, pager, next"
              />
            </div>
          </el-dialog>

          <el-dialog v-model="deviceDialogVisible" title="设备信息" width="50%">
            <div style="margin-bottom: 20px">
              <el-select
                v-model="selectedDevice"
                placeholder="请选择设备"
                style="width: 200px; margin-right: 10px"
              >
                <el-option
                  v-for="device in availableDevices"
                  :key="device.deviceId"
                  :label="device.name"
                  :value="device.deviceId"
                />
              </el-select>
              <el-button type="primary" @click="handleAddDeviceToRoom"
                >添加</el-button
              >
            </div>
            <el-button></el-button>
            <el-table :data="currentDeviceList" border>
              <el-table-column prop="deviceId" label="设备ID" />
              <el-table-column prop="name" label="设备名称" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="danger"
                    :icon="Minus"
                    @click="handleMtRemoveDevice(scope.row.deviceId)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-dialog>
          <button
            v-if="room.status === 0 || room.status === 4"
            :disabled="room.status !== 0 && room.status !== 4"
            @click="handleUpdateStatus(room)"
          >
            {{ room.status === 0 ? "维护" : "租售" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import debounce from "lodash/debounce";
import { ResizeObserver } from "resize-observer";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Refresh,
  Plus,
  Minus,
  ArrowLeft,
  ArrowRight,
  Close,
} from "@element-plus/icons-vue";
import querystring from "querystring";

const dialogVisible = ref(false);
const editForm = ref({});
const addDialogVisible = ref(false);
const addForm = ref({});
const meetingRooms = ref([]);
const loading = ref(true);
const searchQuery = ref("");
const selectedDeviceId = ref(null);
const getRoomImage = (type) => {
  return type === 0
    ? require("@/assets/classroom.png")
    : require("@/assets/meetingroom.png");
};

const getStatusText = (status) => {
  const statusMap = {
    0: "空闲",
    1: "锁定",
    2: "预定中",
    3: "使用中",
    4: "维护中",
  };
  return statusMap[status] || "未知状态";
};

const handleDelete = async (roomId) => {
  try {
    await ElMessageBox.confirm("确定要删除该会议室吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await axios.put("/api/admin/meetingRoom", { roomId });
    meetingRooms.value = meetingRooms.value.filter(
      (room) => room.roomId !== roomId
    );
  } catch (error) {
    console.error("删除失败:", error);
  }
};

const handleEdit = (room) => {
  editForm.value = room;
  dialogVisible.value = true;
};

const handleSave = async () => {
  try {
    await axios.post("/api/admin/meetingRoom/update", editForm.value);
    ElMessage.success("修改成功");
    dialogVisible.value = false;
    const response = await axios.get("/api/admin/meetingRoom");
    meetingRooms.value = response.data.data;
    meetingRooms.value.forEach((room) => fetchImageCount(room.roomId));
  } catch (error) {
    console.error("修改失败:", error);
    ElMessage.error("修改失败");
  }
};

const currentDeviceList = ref([]);
const deviceDialogVisible = ref(false);
const availableDevices = ref([]);
const selectedDevice = ref(null);

const currentRoomId = ref(null);

const handleMtDeviceInfo = async (room) => {
  currentRoomId.value = room.roomId;
  try {
    const [devicesResponse, availableResponse] = await Promise.all([
      axios.get("/api/admin/meetingRoom/getDevice", {
        params: { roomId: room.roomId },
      }),
      axios.get("/api/admin/meetingRoom/getNoDevice", {
        params: { roomId: room.roomId },
      }),
    ]);
    currentDeviceList.value = devicesResponse.data.data;
    availableDevices.value = availableResponse.data.data;
    deviceDialogVisible.value = true;
  } catch (error) {
    console.error("获取设备信息失败:", error);
    ElMessage.error("获取设备信息失败");
  }
};

const handleAddDeviceToRoom = async () => {
  if (!selectedDevice.value) {
    ElMessage.warning("请先选择设备");
    return;
  }
  try {
    await axios.post(
      "/api/admin/meetingRoom/addDevice",
      querystring.stringify({
        deviceId: selectedDevice.value,
        roomId: currentRoomId.value,
      })
    );
    ElMessage.success("设备添加成功");
    const response = await axios.get("/api/admin/meetingRoom/getDevice", {
      params: { roomId: currentRoomId.value },
    });
    currentDeviceList.value = response.data.data;
  } catch (error) {
    console.error("设备添加失败:", error);
    ElMessage.error("设备添加失败");
  }
};

const handleMtRemoveDevice = async (deviceId) => {
  try {
    await ElMessageBox.confirm("确定要删除该设备吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await axios.post(
      "/api/admin/meetingRoom/deleteDevice",
      querystring.stringify({
        deviceId: deviceId,
        roomId: currentRoomId.value,
      })
    );
    ElMessage.success("删除成功");
    const [devicesResponse, availableResponse] = await Promise.all([
      axios.get("/api/admin/meetingRoom/getDevice", {
        params: { roomId: currentRoomId.value },
      }),
      axios.get("/api/admin/meetingRoom/getNoDevice", {
        params: { roomId: currentRoomId.value },
      }),
    ]);
    currentDeviceList.value = devicesResponse.data.data;
    availableDevices.value = availableResponse.data.data;
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error(error.response?.data?.message || "删除失败");
  }
};
const deviceList = ref([]);
const deviceVisible = ref(false);

const handleDeviceInfo = async () => {
  try {
    const response = await axios.get("/api/admin/device");
    deviceList.value = response.data.data;
    deviceVisible.value = true;
  } catch (error) {
    console.error("获取设备信息失败:", error);
    ElMessage.error("获取设备信息失败");
  }
};

const handleAddDevice = async () => {
  try {
    const inputValue = prompt("请输入设备名称");
    if (inputValue) {
      await axios.post(
        "/api/admin/device",
        querystring.stringify({ name: inputValue })
      );
      ElMessage.success("设备添加成功");
      const response = await axios.get("/api/admin/device");
      deviceList.value = response.data.data;
    }
  } catch (error) {
    console.error("设备添加失败:", error);
    ElMessage.error("设备添加失败");
  }
};

const handleSearch = debounce(async () => {
  try {
    const response = await axios.get("/api/admin/meetingRoom/search", {
      params: {
        FuzzyName: searchQuery.value,
      },
    });
    meetingRooms.value = response.data.data;
    meetingRooms.value.forEach((room) => fetchImageCount(room.roomId));
    response.data.data.forEach((room) => {
      fetchImageCount(room.roomId);
    });
  } catch (error) {
    console.error("搜索失败:", error);
    ElMessage.error("搜索失败");
  }
}, 300);

const handleAdd = async () => {
  try {
    await axios.post("/api/admin/meetingRoom/add", addForm.value);
    ElMessage.success("新增成功");
    addDialogVisible.value = false;
    const response = await axios.get("/api/admin/meetingRoom");
    meetingRooms.value = response.data.data;
    meetingRooms.value.forEach((room) => fetchImageCount(room.roomId));
  } catch (error) {
    console.error("新增失败:", error);
    ElMessage.error("新增失败");
  }
};

const statusDialogVisible = ref(false);
const statusData = ref([]);
const currentStatusRoomId = ref(null);
const dateRange = ref([new Date(), new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)]);

const handleViewStatus = async (room) => {
  currentStatusRoomId.value = room.roomId;
  try {
    const response = await axios.post('/api/admin/meetingRoom/showStatus',querystring.stringify( {
      roomId: room.roomId,
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    }));
    statusData.value = response.data.data;
    statusDialogVisible.value = true;
  } catch (error) {
    console.error('获取状态失败:', error);
    ElMessage.error('获取状态失败');
  }
};

const statusTextMap = {
  0: '空闲',
  1: '锁定',
  2: '预定',
  3: '使用',
  4: '维护'
};

const processOverlapTime = (data) => {
  const sorted = [...data].sort((a, b) => 
    new Date(a.startTime) - new Date(b.startTime) || b.status - a.status
  );

  const result = [];
  let current = null;

  for (const item of sorted) {
    if (!current) {
      current = { ...item };
      continue;
    }

    const currentEnd = new Date(current.endTime);
    const itemStart = new Date(item.startTime);

    if (itemStart < currentEnd) {
      if (item.status > current.status) {
        current.endTime = item.startTime;
        result.push(current);
        current = { ...item };
      } else {
        current.endTime = new Date(Math.max(currentEnd, new Date(item.endTime)));
      }
    } else {
      result.push(current);
      current = { ...item };
    }
  }

  if (current) result.push(current);
  return result.map(item => ({
    ...item,
    startTime: formatDate(new Date(item.startTime)),
    endTime: formatDate(new Date(item.endTime)),
    statusText: statusTextMap[item.status]
  }));
};

const handleRefreshStatus = async () => {
  if (!currentStatusRoomId.value) return;
  try {
    const response = await axios.post('/api/admin/meetingRoom/showStatus', querystring.stringify({
      roomId: currentStatusRoomId.value,
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    }));
    statusData.value = processOverlapTime(response.data.data);
    ElMessage.success('刷新成功');
  } catch (error) {
    console.error('刷新状态失败:', error);
    ElMessage.error('刷新状态失败');
  }
};


const formatDate = (date) => {
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};


const getStatusColor = (status) => {
  const colors = {
    0: 'transparent',
    1: '#800080',
    2: '#FFA500',
    3: '#FF0000',
    4: '#008000'
  };
  return colors[status] || 'transparent';
};

const handleUpdateStatus = async (room) => {
  try {
    if (room.status === 0) {
      room.status = 4;
    } else {
      room.status = 0;
    }

    await axios.post("/api/admin/meetingRoom/update", room);
    ElMessage.success("修改成功");
    const response = await axios.get("/api/admin/meetingRoom");
    meetingRooms.value = response.data.data;
    meetingRooms.value.forEach((room) => fetchImageCount(room.roomId));
  } catch (error) {
    console.error("修改失败:", error);
    ElMessage.error("修改失败");
  }
};
const commentCounts = ref({});

const handleViewComments = async (room) => {
  currentCommentRoomId.value = room.roomId;
  commentPagination.value.pageNo = 1;
  try {
    const response = await axios.get("/api/comment/getFrtComment", {
      params: {
        roomId: room.roomId,
        pageNo: commentPagination.value.pageNo,
      },
    });
    commentList.value = response.data.data.list;
    commentPagination.value = {
      pageNo: response.data.data.pageNo,
      pageSize: response.data.data.pageSize,
      pageTotal: response.data.data.pageTotal,
      totalCount: response.data.data.totalCount,
    };
    commentDialogVisible.value = true;
  } catch (error) {
    console.error("获取评论失败:", error);
    ElMessage.error("获取评论失败");
  }
};


const getDaysInRange = (start, end) => {
  const days = [];
  const current = new Date(start);
  const endDate = new Date(end);
  
  while (current <= endDate) {
    days.push(new Date(current));
    current.setDate(current.getDate() + 1);
  }
  
  return days;
};

const formatDayHeader = (date) => {
  return `${date.getMonth() + 1}月${date.getDate()}日`;
};

const getHourBlockStyle = (day, hour) => {
  const dayStart = new Date(day);
  dayStart.setHours(hour, 0, 0, 0);
  const dayEnd = new Date(day);
  dayEnd.setHours(hour + 1, 0, 0, 0);
  
  const matchingStatus = statusData.value.find(item => {
    const itemStart = new Date(item.startTime);
    const itemEnd = new Date(item.endTime);
    return itemStart < dayEnd && itemEnd > dayStart;
  });
  
  if (matchingStatus) {
    const itemStart = new Date(matchingStatus.startTime);
    const itemEnd = new Date(matchingStatus.endTime);
    const startRatio = Math.max(0, (itemStart - dayStart) / (dayEnd - dayStart));
    const endRatio = Math.min(1, (itemEnd - dayStart) / (dayEnd - dayStart));
    
    return {
      background: `linear-gradient(to bottom, 
        ${getStatusColor(matchingStatus.status)} ${startRatio * 100}%, 
        ${getStatusColor(matchingStatus.status)} ${endRatio * 100}%)`,
      'border-radius': '2px'
    };
  }
  
  return {};
};

const commentTimers = ref({});

const toggleSubComments = async (commentId) => {
  expandedComments.value[commentId] = !expandedComments.value[commentId];

  if (expandedComments.value[commentId]) {
    try {
      const response = await axios.get("/api/comment/getSecondComment", {
        params: { commentId },
      });
      subComments.value[commentId] = response.data.data;
      // 启动定时刷新
      commentTimers.value[commentId] = setInterval(async () => {
        try {
          const response = await axios.get("/api/comment/getSecondComment", {
            params: { commentId },
          });
          subComments.value[commentId] = response.data.data;
        } catch (error) {
          console.error("定时获取二级评论失败:", error);
        }
      }, 2000);
    } catch (error) {
      console.error("获取二级评论失败:", error);
      ElMessage.error("获取二级评论失败");
    }
  } else {
    // 清除定时器
    if (commentTimers.value[commentId]) {
      clearInterval(commentTimers.value[commentId]);
      delete commentTimers.value[commentId];
    }
  }
};

// 组件卸载时清理所有定时器
onUnmounted(() => {
  Object.values(commentTimers.value).forEach(timer => {
    clearInterval(timer);
  });
  commentTimers.value = {};
});


const handleCommentPageChange = async (pageNo) => {
  commentPagination.value.pageNo = pageNo;
  try {
    const response = await axios.get("/api/comment/getFrtComment", {
      params: {
        roomId: currentCommentRoomId.value,
        pageNo: pageNo,
      },
    });
    commentList.value = response.data.data.list;
  } catch (error) {
    console.error("获取评论失败:", error);
    ElMessage.error("获取评论失败");
  }
};

const handleRemoveDevice = async (deviceId) => {
  try {
    await ElMessageBox.confirm("确定要删除该设备吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await axios.post(
      "/api/admin/device/delete",
      querystring.stringify({ deviceId: deviceId })
    );
    ElMessage.success("删除成功");
    selectedDeviceId.value = null;
    const response = await axios.get("/api/admin/device");
    deviceList.value = response.data.data;
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error(error.response?.data?.message || "删除失败");
  }
};
const imageCounts = ref({});
const commentDialogVisible = ref(false);
const timers = ref([]);

watch(commentDialogVisible, (newVal) => {
  if (!newVal) {
    Object.values(commentTimers.value).forEach(timer => {
    clearInterval(timer);
  });
  commentTimers.value = {};
  }
});
const commentList = ref([]);
const subComments = ref({});
const expandedComments = ref({});
const currentCommentRoomId = ref(null);
const commentPagination = ref({
  pageNo: 1,
  pageSize: 10,
  pageTotal: 0,
  totalCount: 0,
});

const fetchImageCount = async (roomId) => {
  try {
    const response = await axios.get("/api/admin/meetingRoom/imageCount", {
      params: { roomId },
    });
    imageCounts.value[roomId] = response.data.data;
  } catch (error) {
    console.error("获取图片数量失败:", error);
  }
};

const fetchCommentCount = async (roomId) => {
  try {
    const response = await axios.get("/api/comment/getCommentCount", {
      params: { roomId },
    });
    commentCounts.value[roomId] = response.data.data;
  } catch (error) {
    console.error("获取评论数量失败:", error);
  }
};
const resizeObserver = ref(null);

onMounted(async () => {
  try {
    const response = await axios.get("/api/admin/meetingRoom");
    meetingRooms.value = response.data.data;
    meetingRooms.value.forEach((room) => {
      fetchImageCount(room.roomId);
      fetchCommentCount(room.roomId);
    });

    resizeObserver.value = new ResizeObserver(
      debounce(() => {
        // 处理resize逻辑
      }, 100)
    );
    resizeObserver.value.observe(document.body);
  } catch (error) {
    console.error("获取会议室数据失败:", error);
  } finally {
    loading.value = false;
  }
});

onUnmounted(() => {
  if (resizeObserver.value) {
    resizeObserver.value.disconnect();
  }
  // 释放所有图片URL
  currentImageList.value.forEach((url) => URL.revokeObjectURL(url));
});

const imageDialogVisible = ref(false);
const currentIndex = ref(1);
const currentImageList = ref([]);

// 图片查看方法
const handleViewEnvironment = async (room) => {
  if (imageCounts.value[room.roomId] > 0) {
    currentRoomId.value = room.roomId;
    currentIndex.value = 1;
    try {
      const response = await axios.get("/api/admin/meetingRoom/getImg", {
        params: {
          roomId: room.roomId,
          index: currentIndex.value,
        },
        responseType: "blob",
      });
      const blob = new Blob([response.data], {
        type: response.headers["content-type"],
      });
      const imageUrl = URL.createObjectURL(blob);
      currentImageList.value[currentIndex.value] = [imageUrl];
      imageDialogVisible.value = true;
    } catch (error) {
      console.error("获取图片失败:", error);
      ElMessage.error("获取图片失败");
    }
  }
};

// 图片切换方法
const prevImage = () => {
  if (currentIndex.value > 1) {
    currentIndex.value--;
    fetchImage();
  }
};

const nextImage = () => {
  if (currentIndex.value < imageCounts.value[currentRoomId.value]) {
    currentIndex.value++;
    fetchImage();
  }
};

const fetchImage = async () => {
  try {
    const response = await axios.get("/api/admin/meetingRoom/getImg", {
      params: {
        roomId: currentRoomId.value,
        index: currentIndex.value,
      },
      responseType: "blob",
    });
    const blob = new Blob([response.data], {
      type: response.headers["content-type"],
    });
    const imageUrl = URL.createObjectURL(blob);
    currentImageList.value[currentIndex.value] = imageUrl;
  } catch (error) {
    console.error("获取图片失败:", error);
  }
};

const handleDeleteImage = async () => {
  try {
    await ElMessageBox.confirm("确定要删除这张图片吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await axios.post(
      "/api/admin/meetingRoom/deleteImg",
      querystring.stringify({
        roomId: currentRoomId.value,
        index: currentIndex.value,
      })
    );

    ElMessage.success("删除成功");
    await fetchImageCount(currentRoomId.value);

    if (currentIndex.value > imageCounts.value[currentRoomId.value]) {
      currentIndex.value = Math.max(1, imageCounts.value[currentRoomId.value]);
    }

    if (imageCounts.value[currentRoomId.value] === 0) {
      imageDialogVisible.value = false;
    } else {
      await fetchImage();
    }
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error(error.response?.data?.message || "删除失败");
  }
};

const beforeUpload = (file) => {
  const isImage = file.type === "image/jpeg" || file.type === "image/png";
  if (!isImage) {
    ElMessage.error("只能上传 JPG/PNG 格式!");
  }
  return isImage;
};

const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    ElMessage.success("上传成功");
    fetchImageCount(currentRoomId.value);
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};

const replyDialogVisible = ref(false);
const replyContent = ref("");


const currentSubCommentId = ref(null);
const currentCommentId = ref(null);
const handleReplySubComment = async (subCommentId, commentId) => {
  replyDialogVisible.value = true;
  currentCommentId.value = commentId;
  currentSubCommentId.value = subCommentId;
};

const handleSubmitReply = async () => {
  try {
    await axios.post("/api/admin/meetingRoom/commentsubmit", {
      commentId: currentCommentId.value,
      replyId: currentSubCommentId.value,
      content: replyContent.value,
    },{
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });

    // 刷新子评论列表
    const response = await axios.get("/api/comment/getSecondComment", {
      params: { commentId: currentCommentId.value },
    });
    subComments.value[currentCommentId.value] = response.data.data;

    // 刷新评论数量
    const countResponse = await axios.get("/api/comment/getCommentCount", {
      params: { roomId: currentCommentRoomId.value },
    });
    commentCounts.value[currentCommentRoomId.value] = countResponse.data.data;

    ElMessage.success("回复成功");
    replyDialogVisible.value = false;
    replyContent.value = "";
  } catch (error) {
    console.error("回复失败:", error);
    ElMessage.error("回复失败");
  }
};
</script>



<style scoped>
.meeting-container {
  padding: 20px;
}

.loading {
  text-align: center;
  font-size: 18px;
  color: #666;
  padding: 20px;
}

.meeting-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.meeting-card {
  width: calc(30% - 20px);
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.room-image {
  width: 95%;
  height: 220px;
  object-fit: cover;
}

.room-info {
  padding: 16px;
}

.room-info h3 {
  margin: 0 0 8px;
  font-size: 16px;
  color: #303133;
}

.room-info p {
  margin: 4px 0;
  font-size: 14px;
  color: #606266;
}

.room-actions {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
}

.room-actions button {
  padding: 5px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
}

.room-actions button:hover {
  background: #f5f7fa;
}

.status-0 {
  color: #67c23a;
}

.status-1 {
  color: #f56c6c;
}

.status-2 {
  color: #e6a23c;
}

.status-3 {
  color: #409eff;
}

.status-4 {
  color: #909399;
}

.selected-device {
  background-color: #f5f7fa;
  font-weight: 500;
}
.image-dialog::v-deep .el-dialog__body {
  background-color: #025e9c;
}

.image-viewer {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-container {
  position: relative;
  max-width: 80vw;
  max-height: 70vh;
  margin: 0 40px;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.pagination {
  margin-top: 10px;
  text-align: center;
}
</style>






